package com.itheima.service.mongo.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.itheima.domain.mongo.FocusUser;
import com.itheima.domain.mongo.Friend;
import com.itheima.domain.mongo.UserLike;
import com.itheima.service.mongo.UserLikeCountService;
import com.itheima.vo.PageBeanVo;
import com.itheima.vo.UserLikeCountVo;
import com.itheima.vo.UserLikeVo;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.ArrayList;
import java.util.List;

@DubboService
public class UserLikeCountServiceImpl implements UserLikeCountService {

    @Autowired
    MongoTemplate mongoTemplate;

    @Override
    public UserLikeCountVo selectCount(Long userId) {
        UserLikeCountVo vo = new UserLikeCountVo();


        //统计 我喜欢的人的数量
        //new Query 条件是userId
        Query query1 = new Query(Criteria.where("userId").is(userId));
        //调用mongoTemplate.count()统计我喜欢的人的数量
        long loveCount = mongoTemplate.count(query1, UserLike.class);


        //统计 喜欢我的人的数量（粉丝）
        //new Query 条件likeUserId=userId
        Query query2 = new Query(Criteria.where("focusUserId").is(userId));
        //调用mongoTemplate.count()统计喜欢我的人的数量
        long fanCount = mongoTemplate.count(query2, FocusUser.class);


        //统计互相喜欢的数量
        //调用mongoTemplate.find(query1,UserLike)查询我喜欢的人的列表
        Long eachLoveCount = mongoTemplate.count(query1, Friend.class);

        vo.setEachLoveCount(eachLoveCount);
        vo.setLoveCount(loveCount);
        vo.setFanCount(fanCount);
        //封装vo返回
        return vo;
    }

    @Override
    public PageBeanVo selectPageByType(Integer type, Long userId, Integer pageNum, Integer pageSize) {
        //初始化UserLike集合
        List<Long> userIds = new ArrayList<>();
        long count = 0L;
        //根据type确实要进行的业务
        switch (type) {
            case 1: //查互相喜欢
            {
                //根据用户id查询朋友列表
                Query query = new Query(Criteria.where("userId").is(userId)).with(Sort.by(Sort.Order.desc("created"))).skip((pageNum - 1) * pageSize).limit(pageSize);

                List<Friend> friendList = mongoTemplate.find(query, Friend.class);

                for (Friend friend : friendList) {
                    userIds.add(friend.getFriendId());
                }

                //统计总数
                count = mongoTemplate.count(query, Friend.class);
                break;
            }
            case 2: {//我喜欢的
                //声明条件
                Query query = new Query(Criteria.where("userId").is(userId)).with(Sort.by(Sort.Order.desc("created"))).skip((pageNum - 1) * pageSize).limit(pageSize);
                //根据条件调用mongoTemplate.find(query, UserLike.class)，赋值给userLikeList
                List<UserLike> userLikes = mongoTemplate.find(query, UserLike.class);
                userLikes.forEach(e -> {userIds.add(e.getLikeUserId());});
                query = new Query(Criteria.where("userId").is(userId));
                //统计总数
                count = mongoTemplate.count(query, FocusUser.class);
                break;
            }
            case 3: {//关注我的(粉丝)
                Query query = new Query(Criteria.where("focusUserId").is(userId)).with(Sort.by(Sort.Order.desc("created"))).skip((pageNum - 1) * pageSize).limit(pageSize);
                //根据条件调用mongoTemplate.find(query, UserLike.class)，赋值给userLikeList
                List<FocusUser> focusUsers = mongoTemplate.find(query, FocusUser.class);
                focusUsers.forEach(e -> {userIds.add(e.getUserId());});
                query = new Query(Criteria.where("focusUserId").is(userId));
                //统计总数
                count = mongoTemplate.count(query, FocusUser.class);
                break;
            }
            /*case 4:{//谁看过我

            }*/
        }

        //封装PageBeanVo并返回
        return new PageBeanVo(pageNum, pageSize, count, userIds);
    }


    @Override
    public void like(Long userId, Integer uid) {

        //把喜欢的人封装到User Like表中
        UserLike like = new UserLike();
        like.setLikeUserId(uid.longValue());
        like.setUserId(userId);
        like.setCreated(System.currentTimeMillis());
        mongoTemplate.save(like);

       //判断我喜欢的人 是否也喜欢我 如果喜欢就成为好友
        Query query = new Query(Criteria.where("userId").is(uid));
        List<UserLike> userLikes = mongoTemplate.find(query, UserLike.class);
        //判断userLikes是否为空
        if (CollUtil.isNotEmpty(userLikes)) {
            //遍历userLikes
            userLikes.forEach(u -> {
                //判断我喜欢的人有没有喜欢我
                if (u.getLikeUserId() == userId) {
                    //如果有自动加好友
                    //填充我的好友表
                    Friend friend = new Friend();
                    friend.setFriendId(uid.longValue()); //好友id
                    friend.setUserId(userId); //我的id
                    friend.setCreated(System.currentTimeMillis()); //时间
                    mongoTemplate.save(friend);
                    //填充他的好友表
                    Friend friendFans = new Friend();
                    friendFans.setFriendId(userId);
                    friendFans.setUserId(uid.longValue());
                    friendFans.setCreated(System.currentTimeMillis());
                    mongoTemplate.save(friendFans);

                }
            });
        }

    }



    @Override
    public void noLike(Long userId, Integer uid) {

        //设置删除的条件
        Query query = new Query(Criteria.where("userId").is(userId.longValue())
                .and("likeUserId").is(uid));
        mongoTemplate.remove(query, UserLike.class);


        //判断我取消喜欢的人是否喜欢我，如果喜欢就从朋友表中删除
        Query query1 = new Query(Criteria.where("userId").is(uid));//我不喜欢的人的   喜欢列表
        List<UserLike> unlikes = mongoTemplate.find(query1, UserLike.class);
        //判断unLikes是否为空
        if (CollUtil.isNotEmpty(unlikes)) {
            unlikes.forEach(userLike -> {
                if (userLike.getLikeUserId() == userId) {
                    Query query2 = new Query(Criteria.where("userId").is(userId).and("friendId").is(uid));
                    mongoTemplate.remove(query2, Friend.class);
                    Query query3 = new Query(Criteria.where("userId").is(uid).and(("friendId")).is(userId));
                    mongoTemplate.remove(query3, Friend.class);
                }
            });
        }

    }
}


